package api

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
	"strings"
	"time"
	"zsc-boot/app/customer/model"
	"zsc-boot/app/customer/model/request"
	"zsc-boot/app/customer/model/response"
	"zsc-boot/app/customer/service"
	msgSvc "zsc-boot/app/message/service"
	layerModel "zsc-boot/app/system_layer/model"
	service2 "zsc-boot/app/system_layer/service"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

type CustomerApi struct {
	svc *service.CustomerSvc
}

func NewCustomerApi() *CustomerApi {
	return &CustomerApi{svc: new(service.CustomerSvc)}
}

func (c *CustomerApi) Create(ctx *gin.Context) {
	var req model.Customer
	_ = ctx.Bind(&req)

	userId := service2.GetUserID(ctx)
	req.UserId = uint(userId)
	req.IsImport = true
	req.UpdateUid = uint(userId)
	req.ImportTime = model.CustomerTime(time.Now().Unix())
	req.AssignedTime = model.CustomerTime(time.Now().Unix())
	req.ChannelId = 1

	if err := orm.GetDb().Create(&req).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	if err := orm.GetDb().Create(&model.CustomerFlowLog{
		CustomerId: req.ID, NewUserId: uint(userId), UserId: uint(userId), Reason: "手动创建"}).Error; err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	web.SuccessResponse(ctx, nil)
}

// MyList 自已名下客户列表
func (c *CustomerApi) MyList(ctx *gin.Context) {
	var req request.CustomerListReq
	_ = ctx.Bind(&req)
	userId := service2.GetUserID(ctx)
	req.UserId = uint(userId)

	list, count, err := c.svc.MyList(req)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	var (
		userInfo layerModel.ServiceUser
	)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	//这里不会为nil
	if userInfo.Role.HideMobile {
		list = c.svc.HideMobile(list)
	}
	web.SuccessListResponse(ctx, list, count, req.Page, req.PageSize)
}

// AllList 所有客户列表
func (c *CustomerApi) AllList(ctx *gin.Context) {
	var req request.CustomerListReq
	_ = ctx.Bind(&req)

	var (
		userId   = service2.GetUserID(ctx)
		userInfo layerModel.ServiceUser
		err      error
	)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	list, count, err := c.svc.AllList(req, userInfo)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	//这里不会为nil
	if userInfo.Role.HideMobile {
		list = c.svc.HideMobile(list)
	}

	web.SuccessListResponse(ctx, list, count, req.Page, req.PageSize)
}

// PublicList 所有客户列表
func (c *CustomerApi) PublicList(ctx *gin.Context) {
	var req request.CustomerListReq
	if err := ctx.Bind(&req); err != nil {
		web.FailResponse(ctx, err, "请求异常")
		return
	}

	var (
		userId   = service2.GetUserID(ctx)
		userInfo layerModel.ServiceUser
		err      error
	)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	list, count, err := c.svc.PublicList(req)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	//这里不会为nil
	if userInfo.Role.HideMobile {
		list = c.svc.HideMobile(list)
	}

	web.SuccessListResponse(ctx, list, count, req.Page, req.PageSize)
}

// MyNext 所有客户列表下一个
func (c *CustomerApi) MyNext(ctx *gin.Context) {
	var req request.CustomerListNextReq
	_ = ctx.Bind(&req)

	var (
		userId   = service2.GetUserID(ctx)
		userInfo layerModel.ServiceUser
		err      error
	)
	req.UserId = uint(userId)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	id, index, err := c.svc.MyListNext(req)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	if id == 0 {
		web.SuccessResponse(ctx, response.NextCustomer{
			PageInfo: core.PageInfo{
				Page:     req.Page,
				PageSize: req.PageSize,
			},
			Customer: model.Customer{},
		})
		return
	}

	if data, err := c.svc.Detail(int(id), userInfo.Role.HideMobile); err != nil {
		web.FailResponse(ctx, err, "查询异常")
	} else {
		web.SuccessResponse(ctx, response.NextCustomer{
			PageInfo: core.PageInfo{
				PageSize: req.PageSize,
				Page:     req.Page + index,
			},
			Customer: data,
		})
	}
}

// PublicNext 公海客户列表下一个
func (c *CustomerApi) PublicNext(ctx *gin.Context) {
	var req request.CustomerListNextReq
	_ = ctx.Bind(&req)

	var (
		userId   = service2.GetUserID(ctx)
		userInfo layerModel.ServiceUser
		err      error
	)
	req.UserId = uint(userId)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	id, index, err := c.svc.PublicListNext(req)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	if id == 0 {
		web.SuccessResponse(ctx, response.NextCustomer{
			PageInfo: core.PageInfo{
				Page:     req.Page,
				PageSize: req.PageSize,
			},
			Customer: model.Customer{},
		})
		return
	}

	page := req.Page
	page += index

	if data, err := c.svc.Detail(int(id), userInfo.Role.HideMobile); err != nil {
		web.FailResponse(ctx, err, "查询异常")
	} else {
		web.SuccessResponse(ctx, response.NextCustomer{
			PageInfo: core.PageInfo{
				PageSize: req.PageSize,
				Page:     page,
			},
			Customer: data,
		})
	}
}

// AllNext 所有客户列表下一个
func (c *CustomerApi) AllNext(ctx *gin.Context) {
	var req request.CustomerListNextReq
	_ = ctx.Bind(&req)

	var (
		userId   = service2.GetUserID(ctx)
		userInfo layerModel.ServiceUser
		err      error
	)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	id, index, err := c.svc.AllListNext(req, userInfo)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	page := req.Page
	page += index

	if id == 0 {
		web.SuccessResponse(ctx, response.NextCustomer{
			PageInfo: core.PageInfo{
				Page:     req.Page,
				PageSize: req.PageSize,
			},
			Customer: model.Customer{},
		})
		return
	}

	if data, err := c.svc.Detail(int(id), userInfo.Role.HideMobile); err != nil {
		web.FailResponse(ctx, err, "查询异常")
	} else {
		web.SuccessResponse(ctx, response.NextCustomer{
			PageInfo: core.PageInfo{
				Page:     page,
				PageSize: req.PageSize,
			},
			Customer: data,
		})
	}
}

// BatchUpdate 批量修改api
func (c *CustomerApi) BatchUpdate(ctx *gin.Context) {
	var req request.BatchUpdate
	_ = ctx.Bind(&req)

	userId := service2.GetUserID(ctx)
	if err := c.svc.BatchUpdate(req, userId); err != nil {
		web.FailResponse(ctx, err, err.Error())
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// Detail 详情api
func (c *CustomerApi) Detail(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)
	userId := service2.GetUserID(ctx)
	userInfo, err := orm.Detail[layerModel.ServiceUser](userId, "Role")
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	if data, e := c.svc.Detail(int(req.ID), userInfo.Role.HideMobile); e != nil {
		web.FailResponse(ctx, e, "服务异常")
	} else {
		web.SuccessResponse(ctx, data)
	}
}

// Update 修改
func (c *CustomerApi) Update(ctx *gin.Context) {
	var req request.CustomerUpdate
	_ = ctx.ShouldBind(&req)

	userId := service2.GetUserID(ctx)
	req.UpdateUid = uint(userId)

	if err := c.svc.Update(req); err != nil {
		web.FailResponse(ctx, err, "")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// Follow 跟进
func (c *CustomerApi) Follow(ctx *gin.Context) {
	var req model.CustomerFollowLog
	_ = ctx.Bind(&req)

	userId := service2.GetUserID(ctx)
	req.UserId = uint(userId)

	if err := c.svc.Follow(req); err != nil {
		web.FailResponse(ctx, err, "")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// Dial 拨号
func (c *CustomerApi) Dial(ctx *gin.Context) {
	customerId := ctx.Query("customerId")

	userId := service2.GetUserID(ctx)

	data, err := orm.Detail[model.Customer](cast.ToInt(customerId))
	if err != nil {
		web.FailResponse(ctx, err, "")
		return
	}

	if msgSvc.GetUserConn(userId, msgSvc.App) == nil {
		web.FailResponse(ctx, nil, "app不在线")
		return
	}
	if err = msgSvc.SendUserMsg(userId, "拨号:"+data.Mobile, msgSvc.App, "dial"); err != nil {
		web.FailResponse(ctx, err, err.Error())
		return
	}
	web.SuccessResponse(ctx, nil)
}

// Collect 收藏
func (c *CustomerApi) Collect(ctx *gin.Context) {
	var req model.Customer
	_ = ctx.Bind(&req)

	if err := c.svc.Collect(req); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// BatchCollect 收藏
func (c *CustomerApi) BatchCollect(ctx *gin.Context) {
	var req request.BatchCollect
	_ = ctx.Bind(&req)

	userID := service2.GetUserID(ctx)
	if err := c.svc.BatchCollect(req, userID); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

func (c *CustomerApi) CronRemind(ctx *gin.Context) {
	c.svc.CronRemind()
	web.FailResponse(ctx, nil, "提醒成功")
}

func (c *CustomerApi) CronClear(ctx *gin.Context) {
	c.svc.CronClear()
	web.SuccessResponse(ctx, "清理成功")
}

// Remind 提醒
func (c *CustomerApi) Remind(ctx *gin.Context) {
	var req model.CustomerFollowRemind
	_ = ctx.Bind(&req)

	if err := c.svc.Remind(req); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

func (c *CustomerApi) AutoAssigned(ctx *gin.Context) {
	if err := c.svc.AutoAssigned(); err != nil {
		web.FailResponse(ctx, err, "自动分配异常")
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

func (c *CustomerApi) ExportMobile(ctx *gin.Context) {
	data, err := c.svc.Export()
	if err != nil {
		web.FailResponse(ctx, err, "查询异常")
		return
	}
	ctx.Header("Content-Type", "text/plain; charset=utf-8")
	ctx.Header("Content-Disposition", "attachment; filename=pc.txt")
	ctx.String(http.StatusOK, strings.Join(data, "\n"))
}
